package com.iwe3.protal.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.iwe3.protal.common.ShoppingGoodsInfo;
import com.iwe3.protal.common.ShoppingGoodsItem;
import com.iwe3.protal.entity.BookEntity;
import com.iwe3.protal.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCarServiceImpl implements IShoppingCarService{
    private  final RedisTemplate redisTemplate;
    private final BookMapper bookMapper;

    public ShoppingCarServiceImpl(@Qualifier("redisTemplate") RedisTemplate redisTemplate, BookMapper bookMapper) {
        this.redisTemplate = redisTemplate;
        this.bookMapper = bookMapper;
    }

    @Override
    public void addShoppingCar(long userId, long bookId) {
        BoundHashOperations bhp=redisTemplate.boundHashOps("USER_SHOPPING_CAR_"+userId);
        ShoppingGoodsItem item = null;
        if(!bhp.hasKey(String.valueOf(bookId))){

            BookEntity book = bookMapper.getById(bookId);

            item = BeanUtil.copyProperties(book, ShoppingGoodsItem.class);

            item.setBuycount(1);
            item.setSumPrice(book.getPrice());
            item.setUserId(userId);
        }else{
            String s = (String) bhp.get(String.valueOf(bookId));
            item = JSONUtil.toBean(s, ShoppingGoodsItem.class);
            item.setBuycount(item.getBuycount() + 1);//原有购买量 + 1
            item.setSumPrice(item.getPrice().multiply(
                    new BigDecimal(item.getBuycount())));
        }
        bhp.put(String.valueOf(bookId), JSONUtil.toJsonStr(item));


    }

    @Override
    public ShoppingGoodsInfo getMyShoppingGoodsInfo(long userId) {
        BoundHashOperations bhp = redisTemplate.boundHashOps("USER_SHOPPING_CAR_" + userId);
        List<String> values = bhp.values();
        BigDecimal totalPrice = new BigDecimal("0.0");
        List<ShoppingGoodsItem> items = new ArrayList<>();
        for (String e : values) {
            ShoppingGoodsItem item = JSONUtil.toBean(e, ShoppingGoodsItem.class);
            totalPrice = totalPrice.add(item.getSumPrice());
            items.add(item);
        }
        return new ShoppingGoodsInfo(items, totalPrice);
    }
}
